package br.com.seosoft.simplecalcfinan;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import au.com.bytecode.opencsv.CSVReader;
import br.com.seosoft.simplecalcfinan.bancoDados.BancoDados;
import br.com.seosoft.simplecalcfinan.utils.ChangeLogDialog;
import br.com.seosoft.simplecalcfinan.utils.Propaganda;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class ImportarCsvIntent extends ActivyGeral {
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	TextView tvNome;
	TextView tvData;
	TextView tvTamanho;
	TextView tvValido;
	ImageButton ibImportarCsv;
	String filePath;
	private AdView adView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// TODO Put your code here

		setContentView(R.layout.importar_csv);

		tvNome = (TextView) findViewById(R.id.tvCsvNome);
		tvData = (TextView) findViewById(R.id.tvCsvData);
		tvTamanho = (TextView) findViewById(R.id.tvCsvTamanho);
		tvValido = (TextView) findViewById(R.id.tvCsvValido);
		ibImportarCsv = (ImageButton) findViewById(R.id.ibImportarCsv);
		Propaganda propaganda = new Propaganda();

		if (!propaganda.verificarClienteJaPago(this)) {
			mostrarBanner();
		}

	}

	// MENU NOVIDADES ALERT DIALOG

	public void novidades() {

		// AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// // Get the layout inflater
		// LayoutInflater inflater = getLayoutInflater();
		//
		// builder.setCancelable(false);
		// builder.setTitle(R.string.novidades);
		//
		// // Inflate and set the layout for the dialog
		// // Pass null as the parent view because its going in the dialog
		// layout
		// builder.setView(inflater.inflate(R.layout.novidades, null))
		// // Add action buttons
		// .setNeutralButton(android.R.string.ok,
		// new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int id) {
		// // sign in the user ...
		// dialog.dismiss();
		// }
		// });
		//
		// AlertDialog dialog = builder.create();
		// dialog.show();
		ChangeLogDialog changeLog = new ChangeLogDialog(this);
		changeLog.show();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		getSupportMenuInflater().inflate(R.menu.menu, menu);

		MenuItem logout = (MenuItem) menu.findItem(R.id.menuSair);

		if (geral.logado == true) {
			logout.setVisible(true);
		}

		if (VERSION.SDK_INT >= 14) {
			menu.findItem(R.id.menuImportarSms).setVisible(true);

		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This is called when the Home (Up) button is pressed
			// in the Action Bar.
			Intent parentActivityIntent = new Intent(this, inicial.class);
			parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(parentActivityIntent);
			finish();
			return true;
		case R.id.menuRate:

			Uri uri = Uri.parse("market://details?id="
					+ getApplicationContext().getPackageName());
			Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(goToMarket);
			return true;
		case R.id.meuNovidades:

			novidades();
			return true;
		case R.id.menuConfig:

			startActivityForResult(new Intent(getApplicationContext(),
					Config.class), 1);

			return true;

		case R.id.menuSair:

			geral.logado = false;

			android.os.Process.killProcess(android.os.Process.myPid());
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		Intent parentActivityIntent = new Intent(this, inicial.class);
		parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(parentActivityIntent);
		finish();
		super.onBackPressed();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		if (adView != null) {
			adView.resume();
		}

		Intent it = getIntent();

		if (it != null) {

			if (it.getData() != null) {

				Uri uri = it.getData();
				filePath = uri.getPath();
				Log.v("log", "recebeu intent: " + filePath);

				File file = new File(filePath);

				tvNome.setText(it.getData().getLastPathSegment());
				tvTamanho.setText(file.length() + " bytes");

				SimpleDateFormat simpleFormat = new SimpleDateFormat(
						"dd/MM/yy  HH:mm:ss");

				String data = simpleFormat
						.format(new Date(file.lastModified()));

				tvData.setText(data);
				validCsv(filePath);

			}
		}
	}

	// AO DESTRUIR
	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (adView != null) {
			adView.pause();
		}

	}

	// FAZ A BARRA DE PROGRESSO PARA LEITURA DO CSV
	public void importCsv(String caminho) {

		EasyTracker.getTracker().sendEvent("Menu importar CSV fica explorador",
				"Importar CSV", "botao importCsv", null);

		// MENU IMPORTAR CSV
		// Registra o Alert Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.alertaImportarCsv);
		builder.setTitle(android.R.string.dialog_alert_title);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setCancelable(true);

		builder.setPositiveButton(R.string.sim,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int id) {

						new PogressdialogCsv2().execute(filePath);
					}
				});

		builder.setNegativeButton(R.string.nao,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						dialog.cancel();
					}
				});

		AlertDialog alertDialog = builder.create();
		alertDialog.show();

	}

	class PogressdialogCsv2 extends

	AsyncTask<String, Void, Void> {

		String error;
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {

			progressDialog = new ProgressDialog(ImportarCsvIntent.this);

			progressDialog.setMessage(getResources().getString(
					R.string.carregandoArquivo));

			progressDialog.show();

		}

		@Override
		protected Void doInBackground(String... caminho) {

			try {

				CSVReader reader = new CSVReader(new FileReader(caminho[0]));
				String[] nextLine;
				String grupo = " ";

				int fk_grupo = 0;

				nextLine = reader.readNext();// PULA 1 LINHA .NOME COLUNA

				if (nextLine.length >= 4) {

					BancoDados bd = new BancoDados(ImportarCsvIntent.this,
							false);

					// bd.db.execSQL("DELETE FROM [grupos]");
					// bd.db.execSQL("DELETE FROM [contas]");
					bd.deletaBancoDados();
					bd.recriarBancoDados();

					while ((nextLine = reader.readNext()) != null) {

						if (!nextLine[0].equals(grupo) || grupo == " ") {

							++fk_grupo;

							bd.db.execSQL("INSERT INTO [grupos] ([desc]) VALUES ('"
									+ nextLine[0] + "');");

							Log.v(geral.LogCat, "IMPORT CSV GRUPO: "
									+ nextLine[0]);

							grupo = nextLine[0];

							Log.v(geral.LogCat, "IMPORT CSV FK_GRUPO "
									+ fk_grupo);

						}

						if (nextLine[1] != "") {

							Log.v(geral.LogCat, "IMPORT CSV CONTA: "
									+ nextLine[1]);
							Log.v(geral.LogCat, "IMPORT CSV SALDO: "
									+ nextLine[2]);
							Log.v(geral.LogCat, "IMPORT CSV DATA: "
									+ nextLine[3]);

							bd.db.execSQL("INSERT INTO [contas] ([desc],[fk_grupo],[saldo],[data_time]) VALUES ('"
									+ nextLine[1]
									+ "',"
									+ fk_grupo
									+ ","
									+ nextLine[2] + ",'" + nextLine[3] + "');");

						}

					}
					reader.close();
					bd.fechar();

				} else {

					if (nextLine.length >= 3) {

						BancoDados bd = new BancoDados(ImportarCsvIntent.this,
								true);

						// bd.db.execSQL("DELETE FROM [grupos]");
						// bd.db.execSQL("DELETE FROM [contas]");
						bd.deletaBancoDados();
						bd.recriarBancoDados();

						while ((nextLine = reader.readNext()) != null) {

							if (!nextLine[0].equals(grupo) || grupo == " ") {

								++fk_grupo;

								bd.db.execSQL("INSERT INTO [grupos] ([desc]) VALUES ('"
										+ nextLine[0] + "');");

								Log.v(geral.LogCat, "IMPORT CSV GRUPO: "
										+ nextLine[0]);

								grupo = nextLine[0];

								Log.v(geral.LogCat, "IMPORT CSV FK_GRUPO "
										+ fk_grupo);

							}

							if (nextLine[1] != "") {

								Log.v(geral.LogCat, "IMPORT CSV CONTA: "
										+ nextLine[1]);
								Log.v(geral.LogCat, "IMPORT CSV SALDO: "
										+ nextLine[2]);

								bd.db.execSQL("INSERT INTO [contas] ([desc],[fk_grupo],[saldo]) VALUES ('"
										+ nextLine[1]
										+ "',"
										+ fk_grupo
										+ ","
										+ nextLine[2] + ");");

							}

						}
						reader.close();
						bd.fechar();

					} else {
						error = "Erro CSV";
					}

				}

			} catch (IOException e) {

				error = e.getMessage();
				Log.e(geral.LogCat, "IMPORT CSV ERROR", e);
			}

			return null;

		}

		@Override
		protected void onPostExecute(Void result) {

			progressDialog.dismiss();

			Intent parentActivityIntent = new Intent(getApplicationContext(),
					inicial.class);
			parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(parentActivityIntent);
			finish();

		}
	}

	// FAZ A BARRA DE PROGRESSO PARA LEITURA DO CSV
	public void validCsv(String caminho) {
		new PogressdialogCsv().execute(caminho);
	}

	class PogressdialogCsv extends

	AsyncTask<String, Void, Void> {

		String error;
		private ProgressDialog progressDialog;

		private Boolean valido;

		@Override
		protected void onPreExecute() {

			progressDialog = new ProgressDialog(ImportarCsvIntent.this);

			progressDialog.setMessage(getResources().getString(
					R.string.carregandoArquivo));

			progressDialog.show();

		}

		@Override
		protected Void doInBackground(String... caminho) {

			try {

				CSVReader reader = new CSVReader(new FileReader(caminho[0]));
				String[] nextLine;

				nextLine = reader.readNext();// PULA 1 LINHA .NOME COLUNA

				if (nextLine.length >= 3) {

					valido = true;

				} else {
					valido = false;
				}
				reader.close();

			} catch (IOException e) {

				error = e.getMessage();
				Log.e(geral.LogCat, "IMPORT CSV ERROR", e);
				Tracker myTracker = EasyTracker.getTracker(); // Get a reference
																// to tracker.
				myTracker.sendException(e.getMessage(), true); // false
																// indicates
																// non-fatal
																// exception.
			}

			return null;

		}

		@Override
		protected void onPostExecute(Void result) {

			progressDialog.dismiss();
			setValidCsv(valido);

		}

	}

	public void setValidCsv(Boolean valido) {

		if (valido == true) {

			tvValido.setText(R.string.csvValido);
			tvValido.setTextColor(Color.parseColor("#1c8e14"));
			ibImportarCsv.setEnabled(true);

			ibImportarCsv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					importCsv(filePath);

				}
			});

		} else {

			tvValido.setText(R.string.csvInvalido);
			tvValido.setTextColor(Color.RED);
			ibImportarCsv.setEnabled(false);
		}

	}

	// exibe banner google
	public void mostrarBanner() {

		if (!preference.getBoolean(geral.REMOVEU_ADS, true)) {

			// RevMobBanner banner = revmob.createBanner(this);
			// ViewGroup view = (ViewGroup) findViewById(R.id.bannerCsv);
			// view.addView(banner);

			// Create the adView
			adView = new AdView(this);
			adView.setAdUnitId(geral.id_AdMob);
			adView.setAdSize(AdSize.BANNER);

			// Lookup your LinearLayout assuming it���s been given
			// the attribute android:id="@+id/mainLayout"
			LinearLayout layout = (LinearLayout) findViewById(R.id.bannerCsv);

			// Add the adView to it
			layout.addView(adView);

			// Initiate a generic request to load it with an ad
			AdRequest request = new AdRequest.Builder().build();

			// request.addTestDevice(AdRequest.TEST_EMULATOR);// Emulador
			// request.addTestDevice("emulator-5554");// Testar dispositivo
			// Android
			adView.loadAd(request);
		}

	}

	// MENU IMPORTAR CSV

	public void menuImportarCsv() {

		// Registra o Alert Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.alertaImportarCsv);
		builder.setTitle(android.R.string.dialog_alert_title);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setCancelable(true);

		builder.setPositiveButton(R.string.sim,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int id) {

					}
				});

		builder.setNegativeButton(R.string.nao,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						dialog.cancel();
					}
				});

		AlertDialog alertDialog = builder.create();
		alertDialog.show();

	}
}
